package cate.game.doc;

import cate.game.client.msg.Msg;
import cate.game.client.msg.MsgInput;
import cate.game.client.msg.MsgOutput;
import cp.dev.doc.MsgDictionary;
import cp.dev.doc.MsgMeta;
import easy.java.codec.JsonCodec;
import easy.java.io.file.FileWrite;
import easy.java.runtime.ClassScanner;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Modifier;
import java.util.Comparator;
import java.util.Set;

@Slf4j
public class DocMaker {

    public static void main(String[] args) {
        MsgDictionary dictionary = new MsgDictionary();
        ClassScanner scanner = new ClassScanner();
        Set<Class<?>> clzSet = scanner.getClasses("cate.game", true);
        for(Class<?> clz : clzSet) {
            if(MsgInput.class.isAssignableFrom(clz) && !clz.isInterface() && !Modifier.isAbstract(clz.getModifiers())) {
                try {
                    MsgInput input = (MsgInput)clz.getDeclaredConstructor().newInstance();
                    log.info("input:{}", input.conf());
                    MsgMeta meta = createMsgMeta(input);
                    meta.read(dictionary, clz);
                    dictionary.addMsg(meta);
                } catch (Exception e) {
                    log.error("", e);
                }
            } else if(MsgOutput.class.isAssignableFrom(clz) &&!clz.isInterface()&& !Modifier.isAbstract(clz.getModifiers())) {
                try {
                    MsgOutput output = (MsgOutput)clz.getDeclaredConstructor().newInstance();
                    log.info("output:{}", output.conf());
                    MsgMeta meta = createMsgMeta(output);
                    meta.read(dictionary, clz);
                    dictionary.addMsg(meta);
                } catch (Exception e) {
                    log.error("", e);
                }
            }
        }
        dictionary.msgList.sort(Comparator.comparingInt(o -> o.b));
        DocWriteMsgGroup.write(dictionary);
        log.info("dictionary={}", dictionary);

        try {
            byte[] jsonBytes = JsonCodec.instance().encodeBytes(dictionary);
            FileWrite.i.writeBytes(".tmp/msg.doc.json", jsonBytes);
        } catch (Exception e) {
            log.error("", e);
        }

    }

    private static MsgMeta createMsgMeta(Msg msg) {
        MsgMeta meta = new MsgMeta();
        if(msg.conf() == null) {
            log.error("{}没有配置conf()", msg.getClass());
            return meta;
        }
        meta.a = msg.conf().a;
        meta.b = msg.conf().b;
        meta.codec = msg.conf().codec;
        meta.title = msg.conf().title;
        meta.detail = msg.conf().detail;
        return meta;
    }
}
